package com.keguoyu.easymvp.compiler.base;

import java.io.Writer;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;

import com.keguoyu.easymvp.annotation.CreatedBy;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;

public abstract class BaseProcessor extends AbstractProcessor {

  protected Types mTypeUtils;
  protected Elements mElementUtils;
  protected Filer mFiler;
  protected Messager mMessager;
  protected AnnotationSpec mAutoGenerated;

  @Override
  public synchronized void init(ProcessingEnvironment processingEnvironment) {
    super.init(processingEnvironment);
    mTypeUtils = processingEnvironment.getTypeUtils();
    mElementUtils = processingEnvironment.getElementUtils();
    mFiler = processingEnvironment.getFiler();
    mMessager = processingEnvironment.getMessager();
    mAutoGenerated = AnnotationSpec
        .builder(CreatedBy.class)
        .addMember("value", "$S", getClass().getCanonicalName())
        .build();
  }

  protected final void writeClass(String pkg, String cls, TypeSpec.Builder builder) {
    try {
      Writer writer = mFiler.createSourceFile(pkg + "." + cls).openWriter();
      JavaFile.builder(pkg, builder.build()).build().writeTo(writer);
      writer.flush();
      writer.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  protected final void writeClass(ClassBuilder classBuilder) {
    writeClass(classBuilder.mPkg, classBuilder.mCls, classBuilder.mTypeBuilder);
  }


}
